<template>
  <!--  -->
    <h1>
      首页
    </h1>

</template>

<script setup lang="ts">
import { ref, computed, nextTick, onBeforeUnmount ,onMounted} from 'vue'
import {chatHistoryList ,chatHistoryDetail} from '../request/chat'
import { User } from '@element-plus/icons-vue'

/* ---------- 类型 ---------- */
interface Message {
  //role: 'user' | 'assistant'
  role: 'USER' | 'ASSISTANT'
  content?: string
  think?: string
  answer?: string
  showThink?: boolean
}
interface Chat {
  id: string
  title: string
  time: string
  messages: Message[]
}

const getChatHistory = async ()=>{
  let res:any = await chatHistoryList()
  history.value = res;
  // if(res.length>0){
  //   if(history.value.length>0){
  //     history.value = [...history.value, ...res];
  //   }
  // }
}


/* ---------- 数据 ---------- */
const history = ref<Chat[]>([])
const activeIndex = ref(0)
const question = ref('')
const thinking = ref(false)
const bodyRef = ref<HTMLDivElement>()
let es: EventSource | null = null



/* ---------- 新建/初始化 ---------- */
getChatHistory();
const newChat = async () => {
  //等待getChatHistory 执行完毕再执行下面的
  await getChatHistory();
  history.value.unshift({
    id: Date.now().toString(),
    title: '新对话',
    time: new Date().toLocaleTimeString(),
    messages: []
  })
  activeIndex.value = 0
}

if (!history.value.length) {
  newChat()
}

/* 当前会话 */
const cur = computed(() => history.value[activeIndex.value])


/* ---------- 发送 ---------- */
const send = () => {
  const q = question.value.trim()
  if (!q || thinking.value) return
  question.value = ''
  cur.value.messages.push({ role: 'USER', content: q })
  cur.value.messages.push({ role: 'ASSISTANT', think: '', answer: '', showThink: true })
  cur.value.title = q.slice(0, 20)
  thinking.value = true

  es?.close()
  es = new EventSource(`/api/wechat/ai/flux?input=${encodeURIComponent(q)}`)

  let buffer = ''
  es.onmessage = (e) => {
    const txt = e.data
    if (txt === '[DONE]') {
      const last = cur.value.messages[cur.value.messages.length - 1]
      last.showThink = false
      thinking.value = false
      es?.close()
      return
    }
    buffer += txt
    const last = cur.value.messages[cur.value.messages.length - 1]
    const m = buffer.match(/<think>([\s\S]*?)<\/think>/)
    if (m) {
      last.think = m[1].trim()
      last.answer = buffer.replace(m[0], '').trim()
    } else {
      last.answer = buffer.trim()
    }
    nextTick(() => {
      if (bodyRef.value) bodyRef.value.scrollTop = bodyRef.value.scrollHeight
    })
  }

  es.onerror = () => {
    thinking.value = false
    es?.close()
  }
}

//点击历史记录显示数据详情
async function  chatDetail(item,idx){
  activeIndex.value = idx;
  let res = await chatHistoryDetail(item.id)
  item.messages = res
}


/* 小图标 */
const Chevron = ({ open }: { open: boolean }) =>
  h('span', { style: { transform: open ? 'rotate(180deg)' : undefined, display: 'inline-block', transition: '0.2s' } }, '▼')
</script>

<style scoped>
.chat-app {
  display: flex;
  height: 93vh;
  font-family: 'Segoe UI', sans-serif;
  background: #fff;
}
.sidebar {
  width: 260px;
  background: #f7f7f8;
  border-right: 1px solid #e5e5ea;
  display: flex;
  flex-direction: column;
  padding: 12px;
}
.new-btn {
  padding: 10px 14px;
  background: #10a37f;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
}
.new-btn:hover {
  background: #0d8f6f;
}
.history {
  margin-top: 12px;
  overflow-y: auto;
  padding-left: 0;
}
.history li {
  padding: 10px 8px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 4px;
  display: flex;
  flex-direction: column;
  font-size: 14px;
}
.history li.active {
  background: #e5e5ea;
}
.title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
small {
  color: #666;
  font-size: 12px;
}
.main {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 40px;
}
.msg {
  margin-bottom: 20px;
}
.user {
  display: flex;
  justify-content: flex-end;
}
.assistant {
  display: flex;
  justify-content: flex-start;
}
.bubble {
  max-width: 70%;
  word-break: break-word;
  line-height: 1.55;
  border-radius: 12px;
  padding: 12px 16px;
}
.user .bubble {
  background: #10a37f;
  color: #fff;
}
.assistant .bubble {
  background: #f7f7f8;
}
.think-block {
  border-left: 3px solid #10a37f;
  padding-left: 8px;
  margin-bottom: 8px;
}
.think-hd {
  font-size: 13px;
  color: #10a37f;
  cursor: pointer;
}
.think-body {
  margin: 6px 0 0;
  font-size: 13px;
  color: #555;
  white-space: pre-wrap;
  background: #f0f0f2;
  padding: 6px;
  border-radius: 4px;
}
.answer {
  margin-top: 4px;
}
.cursor {
  color: #10a37f;
  animation: blink 1s infinite;
}
@keyframes blink {
  0%, 100% { opacity: 0; }
  50% { opacity: 1; }
}
.editor {
  background: #f7f7f8;
  padding: 20px 40px;
  display: flex;
  gap: 12px;
  align-items: end;
}
.editor textarea {
  flex: 1;
  resize: none;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 12px 14px;
  font-size: 16px;
  outline: none;
}
.editor textarea:focus {
  border-color: #10a37f;
}
.send-btn {
  padding: 10px 22px;
  border: none;
  background: #10a37f;
  color: #fff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 15px;
}
.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.fade-enter-active,
.fade-leave-active {
  transition: all 0.25s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  height: 0;
}
</style>